<template>
  <div class="page-container">
    <div class="control-container">
      <div class="left-panel shrink-panel" :class="isWide?'':'narrow'">
        <div class="shrink-btn-panel">
          <i :class="isWide?'el-icon-arrow-left':'el-icon-arrow-right'" @click="isWide = !isWide" />
        </div>
        <OutletTree
          v-if="isWide"
          @handleNodeClick="handleNodeClick"
        />
      </div>
      <div class="right-panel overflow-x">
        <div class="search-panel">
          <el-form :inline="true" label-width="100">
            <el-form-item label="时间">
              <el-date-picker
                v-model="query.endDate"
                type="year"
                placeholder="选择日期"
                format="yyyy"
                value-format="yyyy"
                :clearable="false"
              />
            </el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button v-loading="exportLoading" type="primary" @click="handleExport">导出</el-button>
            <!--            <el-button v-show="showData" type="primary" @click="handleChange(true)">切换曲线</el-button>-->
            <!--            <el-button v-show="showLine" type="primary" @click="handleChange(false)">切换表格</el-button>-->
          </el-form>
        </div>
        <div class="">
          <div v-if="!showData" class="choose-outlet-panel">请导航树选择对应节点</div>
          <el-table
            v-if="showData"
            ref="multipleTable"
            v-loading="tableLoading"
            class="grid-data-table"
            height="calc(100vh - 320px)"
            :data="tableData"
          >
            <el-table-column fixed="left" align="center" type="index" width="80" />
            <el-table-column fixed="left" prop="realTimeStr" label="时间" width="140" />
            <template v-for="(item, index) in tableHead">
              <el-table-column
                :key="index + '_head'"
                align="center"
                :label="item.label"
              >
                <template v-if="item.listTableColum.length !== 0">
                  <el-table-column
                    v-for="(it, ide) in item.listTableColum.slice(0,2)"
                    :key="ide + 'list'"
                    :prop="it.prop"
                    :label="it.label"
                    min-width="120"
                  />
                </template>
              </el-table-column>
            </template>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import OutletTree from '@/components/Tree/outletTree'
import { selectMouthData } from '@/api/dataQuery/dataQuery'
import { getDatefmt } from '@/utils/common'
export default {
  name: 'YearReport',
  components: {
    OutletTree
  },
  data() {
    return {
      isWide: true,
      dateFmt: 'yyyy',
      tableLoading: true,
      query: {
        startDate: null, endDate: null, outletId: null
      },
      // 存储是列的属性:列的值
      tableData: [],
      tableHead: [],
      radioData: '3t',
      outletName: '',
      showData: false,
      // showLine: false,
      lineLoading: false,
      exportLoading: false,
      chartData: []
    }
  },
  created() {
    const date = new Date()
    this.query.endDate = getDatefmt(date, this.dateFmt)
  },
  methods: {
    handleChange(val) {
      this.showLine = val
      this.handleQuery()
    },
    handleQuery() {
      if (this.query.outletId === null) {
        this.$message.warning('请选择排口')
        return
      }
      if (this.showLine) {
        this.showData = false
        this.handleSelectLine()
      } else {
        this.showData = true
        this.handleSelectTable()
      }
    },
    // 查询曲线
    // handleSelectLine() {
    //   this.lineLoading = true
    //   const query = JSON.parse(JSON.stringify(this.query))
    //   selectHourBrokenData(query).then(res => {
    //     if (res.data.data === null || res.data.data.length === 0) {
    //       this.$message.warning('该排口暂无数据')
    //     } else {
    //       this.chartData = res.data.data
    //     }
    //     this.lineLoading = false
    //   })
    // },

    // 查询表格
    handleSelectTable() {
      this.tableLoading = true
      this.changeDate()
      const query = JSON.parse(JSON.stringify(this.query))
      selectMouthData(query).then(res => {
        this.tableHead = res.data.column
        var recordsTemp = res.data.page.records
        var total = res.data.page.total
        var max = { realTimeStr: '最大值' }
        var min = { realTimeStr: '最小值' }
        var aveValue = { realTimeStr: '平均值' }
        var sum = { realTimeStr: '累计值' }
        if (recordsTemp != null) {
          for (let i = 0; i < recordsTemp.length; i++) {
            var temp = recordsTemp[i]
            // 计算因子 id
            var factorDtoList = temp.factorDtoList
            if (factorDtoList != null) {
              for (let j = 0; j < factorDtoList.length; j++) {
                var factorDto = factorDtoList[j]
                temp['cl_avg' + factorDto.factorLibraryId] = factorDto.avgVal === null ? '--' : factorDto.avgVal
                temp['cl_out' + factorDto.factorLibraryId] = factorDto.emissionsVal === null ? '--' : factorDto.emissionsVal
                temp['cl_zs_avg' + factorDto.factorLibraryId] = factorDto.zsAvgVal === null ? '--' : factorDto.zsAvgVal
                temp['cl_zs_out' + factorDto.factorLibraryId] = factorDto.zsEmissionsVal === null ? '--' : factorDto.zsEmissionsVal
                // 通过对比计算等方式 拼接最大值行最小值行和累计值行
                if (i === 0) {
                  max['cl_avg' + factorDto.factorLibraryId] = factorDto.avgVal === null ? '--' : factorDto.avgVal
                  max['cl_out' + factorDto.factorLibraryId] = factorDto.emissionsVal === null ? '--' : factorDto.emissionsVal
                  max['cl_zs_avg' + factorDto.factorLibraryId] = factorDto.zsAvgVal === null ? '--' : factorDto.zsAvgVal
                  max['cl_zs_out' + factorDto.factorLibraryId] = factorDto.zsEmissionsVal === null ? '--' : factorDto.zsEmissionsVal

                  min['cl_avg' + factorDto.factorLibraryId] = factorDto.avgVal === null ? '--' : factorDto.avgVal
                  min['cl_out' + factorDto.factorLibraryId] = factorDto.emissionsVal === null ? '--' : factorDto.emissionsVal
                  min['cl_zs_avg' + factorDto.factorLibraryId] = factorDto.zsAvgVal === null ? '--' : factorDto.zsAvgVal
                  min['cl_zs_out' + factorDto.factorLibraryId] = factorDto.zsEmissionsVal === null ? '--' : factorDto.zsEmissionsVal

                  sum['cl_avg' + factorDto.factorLibraryId] = factorDto.avgVal
                  sum['cl_out' + factorDto.factorLibraryId] = factorDto.emissionsVal
                  sum['cl_zs_avg' + factorDto.factorLibraryId] = factorDto.zsAvgVal
                  sum['cl_zs_out' + factorDto.factorLibraryId] = factorDto.zsEmissionsVal

                  aveValue['cl_avg' + factorDto.factorLibraryId] = factorDto.avgVal
                  aveValue['cl_out' + factorDto.factorLibraryId] = factorDto.emissionsVal
                  aveValue['cl_zs_avg' + factorDto.factorLibraryId] = factorDto.zsAvgVal
                  aveValue['cl_zs_out' + factorDto.factorLibraryId] = factorDto.zsEmissionsVal
                } else {
                  if (factorDto.avgVal != null) {
                    if (max['cl_avg' + factorDto.factorLibraryId] < factorDto.avgVal) {
                      max['cl_avg' + factorDto.factorLibraryId] = factorDto.avgVal
                    }
                    if (min['cl_avg' + factorDto.factorLibraryId] > factorDto.avgVal) {
                      min['cl_avg' + factorDto.factorLibraryId] = factorDto.avgVal
                    }
                  }
                  sum['cl_avg' + factorDto.factorLibraryId] = sum['cl_avg' + factorDto.factorLibraryId] + factorDto.avgVal
                  aveValue['cl_avg' + factorDto.factorLibraryId] = sum['cl_avg' + factorDto.factorLibraryId] / total
                  if (factorDto.emissionsVal != null) {
                    if (max['cl_out' + factorDto.factorLibraryId] < factorDto.emissionsVal) {
                      max['cl_out' + factorDto.factorLibraryId] = factorDto.emissionsVal
                    }
                    if (min['cl_out' + factorDto.factorLibraryId] > factorDto.emissionsVal) {
                      min['cl_out' + factorDto.factorLibraryId] = factorDto.emissionsVal
                    }
                  }
                  sum['cl_out' + factorDto.factorLibraryId] = sum['cl_out' + factorDto.factorLibraryId] + factorDto.emissionsVal
                  aveValue['cl_out' + factorDto.factorLibraryId] = sum['cl_out' + factorDto.factorLibraryId] / total
                  if (factorDto.zsAvgVal != null) {
                    if (max['cl_zs_avg' + factorDto.factorLibraryId] < factorDto.zsAvgVal) {
                      max['cl_zs_avg' + factorDto.factorLibraryId] = factorDto.zsAvgVal
                    }
                    if (min['cl_zs_avg' + factorDto.factorLibraryId] > factorDto.zsAvgVal) {
                      min['cl_zs_avg' + factorDto.factorLibraryId] = factorDto.zsAvgVal
                    }
                  }
                  sum['cl_zs_avg' + factorDto.factorLibraryId] = sum['cl_zs_avg' + factorDto.factorLibraryId] + factorDto.zsAvgVal
                  aveValue['cl_zs_avg' + factorDto.factorLibraryId] = sum['cl_zs_avg' + factorDto.factorLibraryId] / total
                  if (factorDto.zsEmissionsVal != null) {
                    if (max['cl_zs_out' + factorDto.factorLibraryId] < factorDto.zsEmissionsVal) {
                      max['cl_zs_out' + factorDto.factorLibraryId] = factorDto.zsEmissionsVal
                    }
                    if (min['cl_zs_out' + factorDto.factorLibraryId] > factorDto.zsEmissionsVal) {
                      min['cl_zs_out' + factorDto.factorLibraryId] = factorDto.zsEmissionsVal
                    }
                  }
                  sum['cl_zs_out' + factorDto.factorLibraryId] = sum['cl_zs_out' + factorDto.factorLibraryId] + factorDto.zsEmissionsVal
                  aveValue['cl_zs_out' + factorDto.factorLibraryId] = sum['cl_zs_out' + factorDto.factorLibraryId] / total
                }
              }
            }
          }
        }
        for (const sumKey in sum) {
          if (sumKey !== 'realTimeStr') {
            sum[sumKey] = this.formatNum(sum[sumKey], 3)
          }
        }
        for (const aveValueKey in aveValue) {
          if (aveValueKey !== 'realTimeStr') {
            aveValue[aveValueKey] = this.formatNum(aveValue[aveValueKey], 3)
          }
        }
        recordsTemp.push(max)
        recordsTemp.push(min)
        recordsTemp.push(aveValue)
        recordsTemp.push(sum)
        this.tableLoading = false
        this.tableData = recordsTemp
        this.query.total = res.data.page.total
        this.$nextTick(() => {
          this.$refs.multipleTable.doLayout()
          // el-table加ref="multipleTable"
        })
      }).catch(reason => {
        this.tableLoading = false
      })
    },
    formatNum(f, digit) {
      var m = Math.pow(10, digit)
      return parseInt(f * m, 10) / m
    },
    handleNodeClick(data) {
      this.query = {
        ...this.query,
        outletId: null
        // total: 0,
        // page: 1,
        // limit: 20
      }
      if (data.level === 3) {
        this.showData = true
        this.query.outletId = data.id
        this.outletName = data.name
        this.handleQuery()
      } else {
        this.$message.warning('请选择排口')
      }
    },
    handleExport() {
      this.exportLoading = true
      // this.tableHead
      // this.tableData

      import('@/utils/Export2Excel').then(excel => {
        var h1 = [this.outletName + '年报表']
        var h2 = ['时间']
        var h3 = ['']
        var h4 = ['realTimeStr']
        const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ']
        const merges = ['A1:' + arr[this.tableHead.length * 2] + 1, 'A2:A3'] // 合并单元格的数据，如何合并参考上面图片讲解
        var index = 1
        this.tableHead.forEach(item => {
          h1.push('')
          h1.push('')
          h2.push(item.label)
          h2.push('')
          h3.push(item.listTableColum[0].label)
          h3.push(item.listTableColum[1].label)
          h4.push(item.listTableColum[0].prop)
          h4.push(item.listTableColum[1].prop)
          merges.push(arr[index] + 2 + ':' + arr[index + 1] + 2)
          index = index + 2
        })
        const multiHeader =
          [
            h1, h2
          ] // 前两行的表头数据，二维数组，不够的用空白补全
        const header = h3 // 最后一行的表头数据
        const filterVal = h4
        // 这里要注意 header  和 filterVal 的数组长度一定要相等，否则会报错
        const list = this.tableData
        const data = this.formatJson(filterVal, list)
        const styleRows = [1, 2]
        excel.export_json_to_excel({
          multiHeader,
          header,
          merges,
          data,
          styleRows,
          filename: this.outletName + '_' + this.query.startDate + '_' + this.query.endDate + '_年报表'
        })
      })
      this.exportLoading = false
    },
    changeDate() {
      this.query.endDate = this.query.endDate.substring(0, 4)
      this.query.startDate = this.query.endDate + '-01'
      this.query.endDate = this.query.endDate + '-12'
    },
    // 拼接数据
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    }

  }
}
</script>

<style lang="scss" scoped>
</style>
